package com.zhuo.project.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhuo.common.constant.ProjectConstants;
import com.zhuo.common.enums.AuditStatus;
import com.zhuo.common.enums.SendStatus;
import com.zhuo.common.utils.IdUtils;
import com.zhuo.common.utils.SecurityUtils;
import com.zhuo.common.utils.poi.ExcelUtil;
import com.zhuo.framework.aspectj.lang.annotation.Log;
import com.zhuo.framework.aspectj.lang.enums.BusinessType;
import com.zhuo.framework.web.controller.BaseController;
import com.zhuo.framework.web.domain.AjaxResult;
import com.zhuo.framework.web.page.TableDataInfo;
import com.zhuo.project.hms.domain.ZzClinicRefDepot;
import com.zhuo.project.hms.service.IZzClinicRefDepotService;
import com.zhuo.project.k3.domain.ZzMaterial;
import com.zhuo.project.k3.service.IZzMaterialService;
import com.zhuo.project.order.domain.ZzDiagnoseHead;
import com.zhuo.project.order.domain.ZzDiagnoseSend;
import com.zhuo.project.order.domain.ZzDiagnoseSendDeliveryInfo;
import com.zhuo.project.order.service.IZzDiagnoseDetailService;
import com.zhuo.project.order.service.IZzDiagnoseHeadService;
import com.zhuo.project.order.service.IZzDiagnoseSendService;
import com.zhuo.project.system.domain.SysUser;
import com.zhuo.project.system.service.ISysUserService;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @author fuhao  <fuhao@kuaishou.com>
 * Created on 2020-04-05
 */
@Api("配杂项单操作")
@RestController
@RequestMapping("/sundry/send")
public class ZzSundrySendController extends BaseController {
    @Autowired
    private IZzDiagnoseSendService zzDiagnoseSendService;

    @Autowired
    private IZzDiagnoseHeadService zzDiagnoseHeadService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IZzDiagnoseDetailService iZzDiagnoseDetailService;

    @Autowired
    private IZzClinicRefDepotService zzClinicRefDepotService;

    @Autowired
    private IZzMaterialService iZzMaterialService;
    


    @ApiOperation("获取配杂项商品明细列表")
    @ApiImplicitParam(name = "diagnoseId", value = "杂项ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('sundry:head:list')")
    @GetMapping("/list/{diagnoseId}")
    public AjaxResult list(@PathVariable("diagnoseId") String diagnoseId) {
        ZzDiagnoseSend zzDiagnoseSendSearch = new ZzDiagnoseSend();
        zzDiagnoseSendSearch.setDiagnoseId(diagnoseId);
        zzDiagnoseSendSearch.setSendStatus(SendStatus.EQUIP.getCode());
        List<ZzDiagnoseSend> list = zzDiagnoseSendService.selectZzDiagnoseSendList(zzDiagnoseSendSearch);
        String userName = SecurityUtils.getUsername();
        for (ZzDiagnoseSend zzDiagnoseSend : list) {
            if (!userName.equals(zzDiagnoseSend.getEquipBy())) {
                SysUser sysUser = iSysUserService.selectUserByUserName(zzDiagnoseSend.getEquipBy());
                return AjaxResult.error(3008,
                        sysUser.getDept().getDeptName() + " 员工编号:" + sysUser.getUserName() + " 姓名:" + sysUser
                                .getNickName() + "正在操作发杂项，请勿操作");
            }
            Double leftQty = iZzDiagnoseDetailService.getDiagnoseMaterialIdLeftQty(diagnoseId, zzDiagnoseSend.getMaterialId());
            zzDiagnoseSend.setLeftSendQty(leftQty);
        }
        return AjaxResult.success(list);
    }


    /**
     * 新增杂项单发杂项明细
     */
    @ApiOperation("保存配杂项信息")
    @ApiImplicitParam(name = "zzDiagnoseSendList", value = "保存配杂项信息", dataType = "ZzDiagnoseSend")
    @PreAuthorize("@ss.hasPermi('sundry:head:list')")
    @Log(title = "杂项单配杂项批量新增", businessType = BusinessType.INSERT)
    @PostMapping("/batch/add")
    public AjaxResult batchAdd(@RequestBody List<ZzDiagnoseSend> zzDiagnoseSendList) {
        if (null == zzDiagnoseSendList || zzDiagnoseSendList.size() == 0) {
            return AjaxResult.error(3001, "参数错误");
        }
        ZzDiagnoseSend zzDiagnoseSendFirst = zzDiagnoseSendList.get(0);
        String sendId = IdUtils.simpleUUID();
        if (StrUtil.isBlank(zzDiagnoseSendFirst.getDiagnoseId())) {
            return AjaxResult.error(3004, "参数错误");
        } else {
            ZzDiagnoseHead zzDiagnoseHead =
                    zzDiagnoseHeadService.selectZzDiagnoseHeadByDiagnoseId(zzDiagnoseSendFirst.getDiagnoseId());
            if (null == zzDiagnoseHead) {
                return AjaxResult.error(3006, "杂项不存在");
            }
            boolean isCanSave = zzDiagnoseHead.getAuditStatus().equals(AuditStatus.SUCC.getCode())
                    || zzDiagnoseHead.getAuditStatus().equals(AuditStatus.REAUDIT.getCode());
            if (!isCanSave) {
                return AjaxResult.error(3005, "杂项状态不是审核通过");
            }

            /* 判断这期间是否有其它人在操作配杂项 */
            ZzDiagnoseSend zzDiagnoseSendSearch = new ZzDiagnoseSend();
            zzDiagnoseSendSearch.setDiagnoseId(zzDiagnoseHead.getDiagnoseId());
            zzDiagnoseSendSearch.setSendStatus(SendStatus.EQUIP.getCode());
            List<ZzDiagnoseSend> zzDiagnoseSendListSearch =
                    zzDiagnoseSendService.selectZzDiagnoseSendList(zzDiagnoseSendSearch);

            String userName = SecurityUtils.getUsername();
            for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendListSearch) {
                if (!userName.equals(zzDiagnoseSend.getEquipBy())) {
                    SysUser sysUser = iSysUserService.selectUserByUserName(zzDiagnoseSend.getEquipBy());
                    return AjaxResult.error(3013,
                            sysUser.getDept().getDeptName() + " 员工编号:" + sysUser.getUserName() + " 姓名:" + sysUser
                                    .getNickName() + "正在操作配杂项，请勿操作");
                }
                /*保留之前的sendId，否则扫打印的配杂项单会提示错误。 */
                sendId = zzDiagnoseSend.getSendId();
            }
        }

        int itemNo = 0;
        // 校验发杂项数量是否超
        Map<String,Double> diagnoseLeftQty = iZzDiagnoseDetailService.getDiagnoseLeftQty(zzDiagnoseSendFirst.getDiagnoseId());
        for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendList) {
            if (StrUtil.isBlank(zzDiagnoseSend.getDiagnoseId())
                    || StrUtil.isBlank(zzDiagnoseSend.getMaterialId())
                    || zzDiagnoseSend.getSendQty() < 0
            ) {
                return AjaxResult.error(3003, "参数错误");
            }
            if(null == zzDiagnoseSend.getSendQty() || zzDiagnoseSend.getSendQty() == 0 ){
                // 未发杂项的行项目忽略
                continue;
            }
            Double leftSendQty = diagnoseLeftQty.get(zzDiagnoseSend.getMaterialId());
            if(null == leftSendQty){
                return AjaxResult.error(3021, zzDiagnoseSend.getMaterialName() + "商品不在杂项中");
            }
            if(leftSendQty < zzDiagnoseSend.getSendQty()){
                return AjaxResult.error(3015, zzDiagnoseSend.getMaterialName() + "商品超发");
            }
            zzDiagnoseSend.setSendId(sendId);
            zzDiagnoseSend.setSendStatus(SendStatus.EQUIP.getCode());
            itemNo = itemNo + 10;
            zzDiagnoseSend.setItemNo(itemNo);
            zzDiagnoseSend.setEquipBy(SecurityUtils.getUsername());
            zzDiagnoseSend.setIsValid(ProjectConstants.IS_VALID_OK);
            zzDiagnoseSend.setCreateBy(SecurityUtils.getUsername());
            String materialId = zzDiagnoseSend.getMaterialId();
            ZzMaterial zzMaterial = iZzMaterialService.selectZzMaterialByMaterialId(materialId);
            zzDiagnoseSend.setBaseQtyUnit(zzMaterial.getfUnDecimal2());
            zzDiagnoseSend.setBaseQtyUnitName(zzMaterial.getFstoreunitid());
            Date now  = new Date();
            zzDiagnoseSend.setCreateTime(now);
            zzDiagnoseSend.setCreateBy(SecurityUtils.getUsername());
            if(null == zzDiagnoseSend.getLastEquipTime()){
                // 匹配手工发杂项无每一行的交互时间。
                zzDiagnoseSend.setLastEquipTime(now);
            }
        }
        if(zzDiagnoseSendList.size()> 0){
            zzDiagnoseSendService.batchInsertZzDiagnoseSend(zzDiagnoseSendList);
            return AjaxResult.success("成功",sendId);
        }

        return AjaxResult.error(3016,"配杂项信息为空");
    }


    /**
     * 导出杂项单发杂项明细列表
     */
    @PreAuthorize("@ss.hasPermi('sundry:head:list')")
    @Log(title = "杂项单发杂项明细", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZzDiagnoseSend zzDiagnoseSend) {
        List<ZzDiagnoseSend> list = zzDiagnoseSendService.selectZzDiagnoseSendList(zzDiagnoseSend);
        ExcelUtil<ZzDiagnoseSend> util = new ExcelUtil<ZzDiagnoseSend>(ZzDiagnoseSend.class);
        return util.exportExcel(list, "send");
    }


    /**
     * 获取杂项单发杂项仓库
     */
    @ApiOperation("获取发杂项仓库列表")
    @ApiImplicitParam(name = "sendId", value = "发杂项单ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('sundry:head:list')")
    @GetMapping(value = "/{sendId}/getDepotList")
    public AjaxResult getDepotList(@PathVariable("sendId") String sendId) {
        List<ZzDiagnoseSend> zzDiagnoseSendList = zzDiagnoseSendService.selectZzDiagnoseSendBySendId(sendId);
        ZzDiagnoseHead zzDiagnoseHead = zzDiagnoseHeadService.selectZzDiagnoseHeadByDiagnoseId(zzDiagnoseSendList.get(0).getDiagnoseId());
        String deptCode = zzDiagnoseHead.getDeptCode();
        ZzClinicRefDepot zzClinicRefDepot = new ZzClinicRefDepot();
        zzClinicRefDepot.setClinicCode(deptCode);
        zzClinicRefDepot.setIsValid(ProjectConstants.IS_VALID_OK);
        List<ZzClinicRefDepot> zzClinicRefDepotList = zzClinicRefDepotService.selectZzClinicRefDepotList(zzClinicRefDepot);
        return AjaxResult.success(zzClinicRefDepotList);
    }


    @ApiOperation("发杂项接口")
    @ApiImplicitParam(name = "zzDiagnoseSendDeliveryInfo", value = "发杂项接口", dataType = "ZzDiagnoseSendDeliveryInfo")
    @PreAuthorize("@ss.hasPermi('sundry:head:list')")
    @Log(title = "杂项单发杂项", businessType = BusinessType.INSERT)
    @PostMapping("/{sendId}/delivery")
    public AjaxResult sendDelivery(@RequestBody ZzDiagnoseSendDeliveryInfo zzDiagnoseSendDeliveryInfo) {
        if(StrUtil.isBlank(zzDiagnoseSendDeliveryInfo.getSendId())
                ||  StrUtil.isBlank(zzDiagnoseSendDeliveryInfo.getPatientCode())
                || StrUtil.isBlank(zzDiagnoseSendDeliveryInfo.getDepotCode())){
            return AjaxResult.error(3017,"参数错误");
        }
        List<ZzDiagnoseSend>  zzDiagnoseSendList = zzDiagnoseSendService.selectZzDiagnoseSendBySendId(zzDiagnoseSendDeliveryInfo.getSendId());
        if(null == zzDiagnoseSendList || zzDiagnoseSendList.size()==0){
            return AjaxResult.error(3017,zzDiagnoseSendDeliveryInfo.getSendId() + " 杂项配杂项信息不存在");
        }
        ZzDiagnoseSend zzDiagnoseSendFirst = zzDiagnoseSendList.get(0);
        if(!zzDiagnoseSendFirst.getSendStatus().equals(SendStatus.EQUIP.getCode())){
            return AjaxResult.error(3019,zzDiagnoseSendDeliveryInfo.getSendId() + " 杂项配杂项已发");
        }
        String diagnoseId = zzDiagnoseSendFirst.getDiagnoseId();
        ZzDiagnoseHead zzDiagnoseHead = zzDiagnoseHeadService.selectZzDiagnoseHeadByDiagnoseId(diagnoseId);
        if(!zzDiagnoseHead.getAuditStatus().equals(AuditStatus.SUCC.getCode())){
            return AjaxResult.error(3019,diagnoseId + " 杂项审核状态不正确");
        }

        if(!zzDiagnoseHead.getPatientCode().equals(zzDiagnoseSendDeliveryInfo.getPatientCode())){
            return AjaxResult.error(3020,diagnoseId + " 病案号不匹配");
        }

        /* 更新处方发药明细 */
        // 要去hms拉最新的一份数据,
        // TODO: 2020/4/6  等sqlServer部署后再补充上。
        String url = "http://127.0.0.1:8888/diagnose/" + zzDiagnoseSendFirst.getDiagnoseId();
        logger.info("hms请求的url={}",url);
        // String ret = HttpUtils.sendGet(url,null);


        Map<String,Double>  diagnoseLeftQty = iZzDiagnoseDetailService.getDiagnoseLeftQty(zzDiagnoseSendFirst.getDiagnoseId());
        List<ZzDiagnoseSend> updateZzDiagnoseSendList = new ArrayList<ZzDiagnoseSend>();
        StringBuffer errorMsg = new StringBuffer();
        Boolean isError = false;
        Date now = new Date();
        for (ZzDiagnoseSend zzDiagnoseSend : zzDiagnoseSendList) {
            ZzDiagnoseSend updateZzDiagnoseSend = new ZzDiagnoseSend();
            Double leftSendQty = diagnoseLeftQty.get(zzDiagnoseSend.getMaterialId());
            if(null == leftSendQty){
                errorMsg.append(zzDiagnoseSend.getMaterialName() + "商品不在处方中");
                errorMsg.append("\n");
                isError = true;
                continue;
            }

            if(leftSendQty < zzDiagnoseSend.getSendQty()){
                double moreQty = zzDiagnoseSend.getSendQty()-leftSendQty;
                errorMsg.append(zzDiagnoseSend.getMaterialName() + "商品超发,超发数量:" + moreQty);
                errorMsg.append("\n");
                isError = true;
            }
            updateZzDiagnoseSend.setId(zzDiagnoseSend.getId());
            updateZzDiagnoseSend.setDiagnoseId(zzDiagnoseSend.getDiagnoseId());
            updateZzDiagnoseSend.setSendId(zzDiagnoseSend.getSendId());
            updateZzDiagnoseSend.setSendStatus(SendStatus.SEND.getCode());
            updateZzDiagnoseSend.setSendBy(SecurityUtils.getUsername());
            updateZzDiagnoseSend.setSendTime(now);
            updateZzDiagnoseSend.setDeptCode(zzDiagnoseHead.getDeptCode());
            updateZzDiagnoseSend.setDeptName(zzDiagnoseHead.getDeptName());
            updateZzDiagnoseSend.setDepotCode(zzDiagnoseSendDeliveryInfo.getDepotCode());
            updateZzDiagnoseSend.setDepotName(zzDiagnoseSendDeliveryInfo.getDepotName());
            updateZzDiagnoseSend.setUpdateBy(SecurityUtils.getUsername());
            updateZzDiagnoseSend.setUpdateTime(now);
            updateZzDiagnoseSendList.add(updateZzDiagnoseSend);
        }
        if(isError){
            return AjaxResult.error(3022, errorMsg.toString());
        }
        return toAjax(zzDiagnoseSendService.batchUpdate(updateZzDiagnoseSendList));
    }
}
